#!/bin/bash

OLDHOME=$HOME

fetch_product_info()
{
  if [[ "$USER" == "bot-coin" ]]; then
    export HOME=/remote/iosg/home-2/bot-coin
  else
    export HOME=$OLDHOME
  fi

  source $HOME/miniconda3/etc/profile.d/conda.sh
  conda activate coin2_motion_env_migration
  ./pyrunner ./python/coin2/support/product_info/run.py
  conda deactivate
  unset HOME
}

notice_user_report()
{
  if [[ "$USER" == "bot-coin" ]]; then
    export HOME=/remote/iosg/home-2/bot-coin
  else
    export HOME=$OLDHOME
  fi
  source $HOME/miniconda3/etc/profile.d/conda.sh
  conda activate coin2_motion_env_migration
  ./pyrunner  python/coin/experimental/xguo/product_info_alarm.py \
	  --slack=$1 \
	  --from_mail="no-reply@joomo.io" \
	  --to_mail=$2 \
	  --subject="NOTICE: product info fetch report" \
	  --context="" \
	  --branch=$3 \
	  --token_file_path=$4 \
	  --report=product_info_fetch_report.txt
  conda deactivate
  unset HOME
}

show_tbl()
{
  sqlite3 << EOF
create table tbl(mea, symbol, type, info);
.mode csv
.import product_info_fetch_report.csv tbl

.mode column

.headers off
select printf('=================================');
select printf('[Product Info Updated(tick size/min qty change)]');

.width 30, 50, 50
.headers on
select mea, symbol, info from tbl where type == 'UPDATE';

.headers off
select printf('=================================');
select printf('[New Symbols]');
.width 30, 50
.headers on
select mea, symbol from tbl where type == 'ADD';

.headers off
select printf('=================================');
select printf('[Removed Symbols]');
.width 30, 50
.headers on
select mea, symbol from tbl where type == 'REMOVE';
EOF
}

check_pi_update()
{
  find data/coin2/product_info/ -name "*.json" | grep -v old_compat | xargs jq -s "." > old.json
  fetch_product_info
  find data/coin2/product_info/ -name "*.json" | grep -v old_compat | xargs jq -s "." > new.json
  local JQLIB="python/coin/experimental/xguo"
  jq -s -L${JQLIB} 'include "product_info_check"; get_pi_update' new.json old.json > product_info_fetch_report.json
  jq -r -L${JQLIB} 'include "product_info_check"; get_pi_update_tbl' product_info_fetch_report.json  > product_info_fetch_report.csv
  show_tbl > product_info_fetch_report.txt
}

if [ $# -eq 0 ]; then
  # check product info
  check_pi_update
else
  # get slack channel
  slack="@wliang"
  if [ $# -ge 1 ]; then
    slack=$1
  fi
  # get email list
  to_mail="wliang@prestolabs.io"
  if [ $# -ge 2 ]; then
    to_mail=$2
  fi
  # get pr url
  branch=""
  if [ $# -ge 3 ]; then
    branch=$3
  fi
  # get token file path
  token_file_path=""
  if [ $# -ge 4 ]; then
    token_file_path=$4
  fi
  # send users report
  notice_user_report $slack $to_mail $branch $token_file_path
fi
